package com.ggb.reactive.utils

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.OSSClientBuilder
import com.ggb.reactive.extension.log
import java.io.ByteArrayInputStream

data class AliOssUtil(
    val endpoint: String,
    val accessKeyId: String,
    val accessKeySecret: String,
    val bucketName: String
) {

    /**
     * 文件上传
     *
     * @param bytes
     * @param objectName
     * @return
     */
    fun upload(bytes: ByteArray, objectName: String): String {
        // 创建OSSClient实例。
        val ossClient: OSS = OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret)

        try {
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, ByteArrayInputStream(bytes))
        } catch (oe: OSSException) {
            println("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.")
            println("Error Message: ${oe.errorMessage}")
            println("Error Code: ${oe.errorCode}")
            println("Request ID: ${oe.requestId}")
            println("Host ID: ${oe.hostId}")
        } catch (ce: ClientException) {
            println("Caught an ClientException, which means the client encountered a serious internal problem while trying to communicate with OSS, such as not being able to access the network.")
            println("Error Message: ${ce.message}")
        } finally {
            ossClient.shutdown()
        }

        // 文件访问路径规则 https://BucketName.Endpoint/ObjectName
        val filePath = "https://${bucketName}.${endpoint}/${objectName}"
        log.info("文件上传到: {}", filePath)

        return filePath
    }
}